// SmarTest Studio - HomePage类

import { showNotification } from './utils.js';
import { WorkspaceTab } from './workspace-tab.js';
import { TemplateTab } from './template-tab.js';
import { TaskTab } from './task-tab.js';
import { DeviceTab } from './device-tab.js';
import { ReportTab } from './report-tab.js';

/**
 * HomePage类 - 负责管理整个主页的功能
 */
export class HomePage {
    constructor() {
        // 初始化各个标签页
        this.workspaceTab = new WorkspaceTab();
        this.templateTab = new TemplateTab();
        this.taskTab = new TaskTab();
        this.deviceTab = new DeviceTab();
        this.reportTab = new ReportTab();
        
        // 绑定方法到实例
        this.initFlashMessages = this.initFlashMessages.bind(this);
        this.initFullscreenToggle = this.initFullscreenToggle.bind(this);
        this.toggleFullScreen = this.toggleFullScreen.bind(this);
        this.updateFullscreenButtonIcon = this.updateFullscreenButtonIcon.bind(this);
        this.initSidebar = this.initSidebar.bind(this);
    }
    
    /**
     * 初始化页面
     */
    init() {
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化Flash消息
            this.initFlashMessages();
            
            // 初始化Bootstrap工具提示和弹出框
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });

            // 加载初始数据
            this.workspaceTab.loadProjects(); // Initial load without filters
            this.templateTab.loadTemplates();
            this.taskTab.loadTasks();
            this.deviceTab.loadDevices();
            this.reportTab.loadReports();

            // 添加标签切换事件监听器
            document.getElementById('workspace-tab').addEventListener('click', () => this.workspaceTab.loadProjects()); // Reload projects when tab is clicked
            document.getElementById('template-tab').addEventListener('click', () => this.templateTab.loadTemplates());
            document.getElementById('task-tab').addEventListener('click', () => this.taskTab.loadTasks());
            document.getElementById('device-tab').addEventListener('click', () => this.deviceTab.loadDevices());
            document.getElementById('report-tab').addEventListener('click', () => this.reportTab.loadReports());
            
            if(document.getElementById('new_project')){
                document.getElementById('new_project').addEventListener('click', () => this.workspaceTab.newProject());
            }
            
            // 初始化项目工作区搜索和筛选功能
            this.workspaceTab.setupProjectWorkspaceFilters();
            
            // 初始化侧边栏折叠功能
            this.initSidebar();
            
            // 初始化全屏切换功能
            this.initFullscreenToggle();
        });
    }
    
    /**
     * Flash消息处理
     */
    initFlashMessages() {
        const flashMessages = document.querySelector('.flash-messages');
        if (flashMessages && flashMessages.children.length > 0) {
            // 如果有flash消息，给body添加类名以调整布局
            document.body.classList.add('has-flash-messages');
            
            // 自动隐藏flash消息（5秒后）
            setTimeout(() => {
                const alerts = flashMessages.querySelectorAll('.alert');
                alerts.forEach(alert => {
                    const bsAlert = new bootstrap.Alert(alert);
                    bsAlert.close();
                });
                
                // 移除body的类名
                setTimeout(() => {
                    document.body.classList.remove('has-flash-messages');
                }, 300); // 等待动画完成
            }, 5000);
        }
    }
    
    /**
     * 全屏切换功能初始化
     */
    initFullscreenToggle() {
        const fullscreenBtn = document.getElementById('fullscreen-btn');
        if (!fullscreenBtn) return;
        
        fullscreenBtn.addEventListener('click', () => {
            this.toggleFullScreen();
        });
        
        // 监听全屏状态变化，更新按钮图标
        document.addEventListener('fullscreenchange', this.updateFullscreenButtonIcon);
        document.addEventListener('webkitfullscreenchange', this.updateFullscreenButtonIcon);
        document.addEventListener('mozfullscreenchange', this.updateFullscreenButtonIcon);
        document.addEventListener('MSFullscreenChange', this.updateFullscreenButtonIcon);
        
        // 初始化按钮图标
        this.updateFullscreenButtonIcon();
    }
    
    /**
     * 切换全屏状态
     */
    toggleFullScreen() {
        if (!document.fullscreenElement && 
            !document.mozFullScreenElement && 
            !document.webkitFullscreenElement && 
            !document.msFullscreenElement) {
            // 进入全屏
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if (document.documentElement.msRequestFullscreen) {
                document.documentElement.msRequestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
            }
        } else {
            // 退出全屏
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            }
        }
    }
    
    /**
     * 更新全屏按钮图标
     */
    updateFullscreenButtonIcon() {
        const fullscreenBtn = document.getElementById('fullscreen-btn');
        if (!fullscreenBtn) return;
        
        const icon = fullscreenBtn.querySelector('i');
        if (!icon) return;
        
        if (document.fullscreenElement || 
            document.mozFullScreenElement || 
            document.webkitFullscreenElement || 
            document.msFullscreenElement) {
            // 全屏状态 - 显示退出全屏图标
            icon.className = 'bi bi-fullscreen-exit';
            fullscreenBtn.setAttribute('title', '退出全屏');
        } else {
            // 非全屏状态 - 显示进入全屏图标
            icon.className = 'bi bi-fullscreen';
            fullscreenBtn.setAttribute('title', '全屏切换');
        }
    }
    
    /**
     * 初始化侧边栏折叠功能
     */
    initSidebar() {
        const toggleBtn = document.getElementById('toggleSidebar');
        const sidebar = document.getElementById('sidebar');
        
        // 确保侧边栏默认为折叠状态
        if (!sidebar.classList.contains('collapsed')) {
            sidebar.classList.add('collapsed');
        }
        
        // 添加点击事件处理
        toggleBtn.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
        });
    }
    
    /**
     * 防抖函数
     */
    static debounce(func, delay) {
        let timeout;
        return function(...args) {
            const context = this;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), delay);
        };
    }
}

// 创建并初始化HomePage实例
const homePage = new HomePage();
homePage.init();